package com.company.project.utils;



import com.company.project.constants.Constants;
import com.company.project.core.exception.BusinessException;
import com.company.project.core.support.ErrorCode;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 上传文件工具类
 * Created by xuew on 2017/11/29.
 */
public class UploadFileUtil {

    /**
     *
     * @param file  MultipartFile文件
     * @param basePath 服务器根路径
     * @param type 文件类型，从constants中取
     * @return 文件相对路径
     */
    public static String handleUploadFile(MultipartFile file, String basePath, String type) {
        InputStream is = null;//获取输入流
        String originalFilename = file.getOriginalFilename();
        String errorMessage = "上传[" + originalFilename + "]文件失败，";
        if (file.isEmpty()) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "不能上传空文件！");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(Constants.FILE_SUFFIX_SEPARATOR));
        if (StringUtil.isEmpty(suffix)) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "未知的文件类型！");
        }

        if (!type.contains(StringUtil.warpper(suffix.toLowerCase(), "%"))) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "不能上传该类型文件！");
        }

        String fileName = System.currentTimeMillis() + suffix;
        BufferedOutputStream stream = null;
        FileOutputStream fos = null;
        try {
            is = file.getInputStream();
            //获取输出流
            OutputStream os=new FileOutputStream(basePath +File.separator+ Constants.UPLOAD_PATH + fileName);
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            int temp;
            //一个一个字节的读取并写入
            while((temp=is.read())!=(-1))
            {
                os.write(temp);
            }
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, errorMessage + "文件不存在：" + e.getMessage(), e);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, errorMessage + "文件保存出错：" + e.getMessage(), e);
        } finally {
            if (is != null) {
                try { is.close(); } catch (Exception e) {
                    throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, e);
                }
            }
            if (fos != null) {
                try { fos.close(); } catch (Exception e) {
                    throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, e);
                }
            }
            if (stream != null) {
                try { stream.close(); } catch (Exception e) {
                    throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR, e);
                }
            }
        }
        return  Constants.UPLOAD_PATH + fileName;
    }
}
